<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>Document</title>
</head>

<body>
  <div id="time"></div>
  <input type="button" id="btnStart" value="开始" onclick="start()" />
  <input type="button" id="btnStop" value="停止" onclick="stop()" />
</body>
<script>

  //判断当前浏览器是否支持SSE
  let source = null;

  function start() {
    console.log('开始');
    if (source) {
      return console.log('不能重复连接');
    }
    if (!!window.EventSource) {
      let url = 'http://localhost/manage/wxpusher/sse?extra=2yx0zvoekzt';
      url = 'https://substatsbd.cess.cloud/block/query/latest';
      url = "/sse"
      source = new EventSource(url);
      // source = new EventSource('/sse/?id=211');
    } else {
      throw new Error("当前浏览器不支持SSE")
    }

    //对于建立链接的监听
    source.onopen = function (event) {
      // console.log(source.readyState);
      console.log("长连接打开");
    };

    //对服务端消息的监听
    source.onmessage = function (event) {
      console.log(JSON.parse(event.data));
      console.log("收到长连接信息");
      let li = JSON.parse(event.data).message;
      document.getElementById("time").innerHTML = li;
    };

    //对断开链接的监听
    source.onerror = function (event) {
      // console.log(source.readyState);
      console.log("长连接中断,将会重连");
    };
  }
  function stop() {
    source.close();
    source = null;
  }
</script>

</html>